<template>
  <div class="app-container">
    <div class="head-container">
      <!-- 搜索 -->
      <el-input v-model="listQuery.Filter" clearable size="small" placeholder="搜索..." style="width: 200px;"
        class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.OddNumber" clearable size="small" placeholder="请选择..." style="width: 100px;"
        class="filter-item" >
        <el-option v-for="item in OddNumberList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-input v-model="listQuery.OrderNumber" clearable size="small" style="width: 150px;" class="filter-item"
        @keyup.enter.native="handleFilter" placeholder="请输入订单号" />
      买家:
      <el-input v-model="listQuery.Buyer" clearable size="small" placeholder="请输入买家姓名" style="width: 150px;"
        class="filter-item" @keyup.enter.native="handleFilter" />
      运单号:
      <el-select v-model="listQuery.IsOrderNumber" clearable size="small" placeholder="请选择是否有单号" style="width: 150px;"
        class="filter-item">
        <el-option label="有单号" value="true" />
        <el-option label="无单号" value="false" />
      </el-select>
      平台店铺:
      <el-select v-model="listQuery.SelectedValues" multiple filterable allow-create default-first-option
        :reserve-keyword="false" placeholder="请选择平台店铺" style="width: 240px" clearable>
        <el-option-group label="平台">
          <el-option v-for="item in platformOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-option-group>
        <el-option-group label="店铺">
          <el-option v-for="item in storeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-option-group>
      </el-select>

      <el-select v-model="listQuery.SelectedTime" clearable size="small" style="width: 150px;" class="filter-item">
        <el-option label="最晚发货时间" value="最晚发货时间"></el-option>
        <el-option label="下单时间" value="下单时间"></el-option>
        <el-option label="仓库接单时间" value="仓库接单时间"></el-option>
        <el-option label="付款时间" value="付款时间"></el-option>
      </el-select>
      &nbsp;
      <el-radio-group v-model="listQuery.SelectedRange">
        <el-radio label="today" value="today">今天</el-radio>
        <el-radio label="7days" value="7days">近7天</el-radio>
        <el-radio label="30days" value="30days">近30天</el-radio>
      </el-radio-group>

      承运商:
      <el-select v-model="listQuery.Carrier" multiple collapse-tags clearable size="small" placeholder="请选择承运商"
        style="width: 150px;" class="filter-item">

        <el-option v-for="item in CarrierList" :key="item.value" :label="item.label" :value="item.label">
          <el-checkbox :label="item.label" v-model="listQuery.Carrier">{{ item.label }}</el-checkbox>
        </el-option>

      </el-select>

      手机:
      <el-input v-model="listQuery.Phone" clearable size="small" placeholder="请输入手机号" style="width: 150px;"
        class="filter-item" @keyup.enter.native="handleFilter" />

      出库类型:
      <el-select v-model="listQuery.OutboundType" clearable size="small" placeholder="请选择出库类型" style="width: 150px;"
        class="filter-item">
        <el-option v-for="(item, index) in OutboundTypeList" :key="index" :label="item.label" :value="item.label" />
      </el-select>
      
      地区:
      <!-- 地区输入框 -->
      <el-input v-model="listQuery.PickingArea" clearable size="small" style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />

      <!-- 打开地区设置对话框按钮 -->
      <el-button size="small" type="primary" @click="openDialog" icon="el-icon-setting" >地区设置</el-button>


      <!-- 地区设置对话框 -->
      <el-dialog :visible.sync="dialogVisible" title="地区设置" width="800px">
        <el-button @click="selectAll">全选</el-button>
        <el-button @click="selectNone">全不选</el-button>
        <el-button @click="toggleSelection">反选</el-button>

        <div class="content">
          <div class="checkbox-group">
            <div class="item" v-for="province in provinces" :key="province.value">
              <div style="display: flex; align-items: center;">
                <div style="margin-right: 100px;">
                  <el-checkbox :label="province.value" v-model="selectedValues">{{ province.label }}</el-checkbox>
                </div>
                <div style="margin-right: 70px;">
                  <el-checkbox v-for="city in province.children" :key="city.value" :label="city.value"
                    v-model="selectedValues" @change="onCityChange(province, city)">
                    {{ city.label }}
                  </el-checkbox>
                </div>
              </div>
            </div>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection">确定</el-button>
        </span>
      </el-dialog>


      <el-button size="small" class="filter-item" type="success" icon="el-icon-search" @click="handleFilter">搜索</el-button>
       
      <el-button size="small" class="filter-item" type="info" icon="el-icon-plus" @click="">打到零拣</el-button>

      <el-button size="small" class="filter-item" type="warning" icon="el-icon-plus" @click="">手动截单</el-button>
  
      <el-button size="small" slot="reference" class="filter-item" type="danger" icon="el-icon-delete"
        @click="handleDelete()">批量删除</el-button>
    </div>
    <el-table ref="multipleTable" v-loading="listLoading" :data="list" size="small" style="width: 90%;"
      @sort-change="sortChange" @selection-change="handleSelectionChange" @row-click="handleRowClick">
      <el-table-column type="selection" width="44px" fixed></el-table-column>
      <el-table-column label="提醒" prop="reminder" align="center" fixed />
      <el-table-column label="外部状态" prop="externalStatus" align="center" fixed />
      <el-table-column label="买家留言" prop="buyerMessage" align="center" fixed />
      <el-table-column label="订单备注" prop="orderNote" align="center" fixed />
      <el-table-column label="库位库存" prop="locationStock" align="center" fixed />
      <el-table-column label="承运商" prop="carrier" align="center" />
      <el-table-column label="运单号" prop="trackingNumber" align="center" />
      <el-table-column label="配送方式" prop="deliveryMethod" align="center" />
      <el-table-column label="买家" prop="buyer" align="center" />
      <el-table-column label="收货人" prop="consignee" align="center" />
      <el-table-column label="详细地址" prop="detailedAddress" align="center" />
      <el-table-column label="手机" prop="phone" align="center" />
      <el-table-column label="实付" prop="pay" align="center" />
      <el-table-column label="优惠" prop="discount" align="center" />
      <el-table-column label="运费" prop="freight" align="center" />
      <el-table-column label="重量" prop="weight" align="center" />
      <el-table-column label="估重" prop="weightEstimation" align="center" />
      <el-table-column label="商品总数" prop="totalGoods" align="center" />
      <el-table-column label="下单时间" prop="orderTime" align="center" />
      <el-table-column label="订单号" prop="orderNumber" align="center" />
      <el-table-column label="外部订单号" prop="externalOrderNumber" align="center" />
      <el-table-column label="线上订单号" prop="onlineOrderNumber" align="center" />
      <el-table-column label="平台店铺" prop="platformStore" align="center" />
      <el-table-column label="付款时间" prop="paymentTime" align="center" />
      <el-table-column label="仓库接单时间" prop="warehouseOrderTime" align="center" />
      <el-table-column label="炼选区域" prop="pickingArea" align="center" />
      <el-table-column label="出库类型" prop="outboundType" align="center" />
      <el-table-column label="品牌" prop="brand" align="center" />
      <el-table-column label="归属波次" prop="attributionWave" align="center" />
      <el-table-column label="等待超时时间" prop="waitingTimeoutTime" align="center" />
      <el-table-column label="到货时间" prop="arrivalTime" align="center" />
      <el-table-column label="体积" prop="volume" align="center" />
      <el-table-column label="标记" prop="mark" align="center" />
      <el-table-column label="最晚发货时间" prop="latestShipmentTime" align="center" />
      <el-table-column label="剩余发货时间" prop="remainingShipmentTime" align="center" />
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)" icon="el-icon-edit" />
          <el-button type="danger" size="mini" @click="handleDelete(row)" icon="el-icon-delete" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="totalCount>0" :total="totalCount" :page.sync="page"
      :limit.sync="listQuery.MaxResultCount" @pagination="getList" />


    <div>
          
    </div>
  </div>
</template>
<script>
import Pagination from "@/components/Pagination";
import permission from "@/directive/permission/index.js";
const defaultForm = {
  id: null,
  Reminder: null,
  ExternalStatus: null,
  BuyerMessage: null,
  OrderNote: null,
  LocationStock: null,
  Carrier: null,
  TrackingNumber: null,
  DeliveryMethod: null,
  Buyer: null,
  Consignee: null,
  DetailedAddress: null,
  Phone: null,
  Pay: null,
  Discount: null,
  freight: null,
  weight: null,
  WeightEstimation: null,
  TotalGoods: null,
  OrderTime: null,
  OrderNumber: null,
  ExternalOrderNumber: null,
  OnlineOrderNumber: null,
  PlatformStore: null,
  PaymentTime: null,
  WarehouseOrderTime: null,
  PickingArea: null,
  OutboundType: null,
  Brand: null,
  AttributionWave: null,
  WaitingTimeoutTime: null,
  ArrivalTime: null,
  Volume: null,
  Mark: null,
  LatestShipmentTime: null,
  RemainingShipmentTime: null,
}
export default {
  name: 'WaitingOutbound',
  components: {
    Pagination
  },
  directives: {
    permission
  },
  props: [],
  data() {
    return {
      // rules: {
      //   Reminder: [{
      //     required: true,
      //     message: '请输入提醒',
      //     trigger: 'blur'
      //   }],
      //   ExternalStatus: [{
      //     required: true,
      //     message: '请输入外部状态',
      //     trigger: 'blur'
      //   }],
      //   BuyerMessage: [{
      //     required: true,
      //     message: '请输入买家留言',
      //     trigger: 'blur'
      //   }],
      //   OrderNote: [{
      //     required: true,
      //     message: '请输入订单备注',
      //     trigger: 'blur'
      //   }],
      //   LocationStock: [{
      //     required: true,
      //     message: '请输入库位库存',
      //     trigger: 'blur'
      //   }],
      //   Carrier: [{
      //     required: true,
      //     message: '请输入承运商',
      //     trigger: 'blur'
      //   }],
      //   TrackingNumber: [{
      //     required: true,
      //     message: '请输入运单号',
      //     trigger: 'blur'
      //   }],
      //   DeliveryMethod: [{
      //     required: true,
      //     message: '请输入配送方式',
      //     trigger: 'blur'
      //   }],
      //   Buyer: [{
      //     required: true,
      //     message: '请输入买家',
      //     trigger: 'blur'
      //   }],
      //   Consignee: [{
      //     required: true,
      //     message: '请输入收货人',
      //     trigger: 'blur'
      //   }],
      //   DetailedAddress: [{
      //     required: true,
      //     message: '请输入详细地址',
      //     trigger: 'blur'
      //   }],
      //   Phone: [{
      //     required: true,
      //     message: '请输入手机',
      //     trigger: 'blur'
      //   }],
      //   Pay: [{
      //     required: true,
      //     message: '请输入实付',
      //     trigger: 'blur'
      //   }],
      //   Discount: [{
      //     required: true,
      //     message: '请输入优惠',
      //     trigger: 'blur'
      //   }],
      //   freight: [{
      //     required: true,
      //     message: '请输入运费',
      //     trigger: 'blur'
      //   }],
      //   weight: [{
      //     required: true,
      //     message: '请输入重量',
      //     trigger: 'blur'
      //   }],
      //   WeightEstimation: [{
      //     required: true,
      //     message: '请输入估重',
      //     trigger: 'blur'
      //   }],
      //   TotalGoods: [{
      //     required: true,
      //     message: '请输入商品总数',
      //     trigger: 'blur'
      //   }],
      //   OrderTime: [{
      //     required: true,
      //     message: '请输入下单时间',
      //     trigger: 'blur'
      //   }],
      //   OrderNumber: [{
      //     required: true,
      //     message: '请输入订单号',
      //     trigger: 'blur'
      //   }],
      //   ExternalOrderNumber: [{
      //     required: true,
      //     message: '请输入外部订单号',
      //     trigger: 'blur'
      //   }],
      //   OnlineOrderNumber: [{
      //     required: true,
      //     message: '请输入线上订单号',
      //     trigger: 'blur'
      //   }],
      //   PlatformStore: [{
      //     required: true,
      //     message: '请输入平台店铺',
      //     trigger: 'blur'
      //   }],
      //   PaymentTime: [{
      //     required: true,
      //     message: '请输入付款时间',
      //     trigger: 'blur'
      //   }],
      //   WarehouseOrderTime: [{
      //     required: true,
      //     message: '请输入仓库接单时间',
      //     trigger: 'blur'
      //   }],
      //   PickingArea: [{
      //     required: true,
      //     message: '请输入炼选区域',
      //     trigger: 'blur'
      //   }],
      //   OutboundType: [{
      //     required: true,
      //     message: '请输入出库类型',
      //     trigger: 'blur'
      //   }],
      //   Brand: [{
      //     required: true,
      //     message: '请输入品牌',
      //     trigger: 'blur'
      //   }],
      //   AttributionWave: [{
      //     required: true,
      //     message: '请输入归属波次',
      //     trigger: 'blur'
      //   }],
      //   WaitingTimeoutTime: [{
      //     required: true,
      //     message: '请输入等待超时时间',
      //     trigger: 'blur'
      //   }],
      //   ArrivalTime: [{
      //     required: true,
      //     message: '请输入到货时间',
      //     trigger: 'blur'
      //   }],
      //   Volume: [{
      //     required: true,
      //     message: '请输入体积',
      //     trigger: 'blur'
      //   }],
      //   Mark: [{
      //     required: true,
      //     message: '请输入标记',
      //     trigger: 'blur'
      //   }],
      //   LatestShipmentTime: [{
      //     required: true,
      //     message: '请输入最晚发货时间',
      //     trigger: 'blur'
      //   }],
      //   RemainingShipmentTime: [{
      //     required: true,
      //     message: '请输入剩余发货时间',
      //     trigger: 'blur'
      //   }],
      // },
      form: Object.assign({}, defaultForm),
      list: null,
      totalCount: 0,
      listLoading: true,
      formLoading: false,
      listQuery: {
        Filter: '',
        Sorting: '',
        SkipCount: 0,
        MaxResultCount: 10,
        OddNumber: "1",
        OrderNumber: '',
        Buyer: '',
        IsOrderNumber: null,
        SelectedValues: [],
        SelectedTime: "最晚发货时间",
        SelectedRange: "7days", // 默认选中"近7天"
        Carrier: [],
        PickingArea: [],
      },
      page: 1,
      dialogFormVisible: false,
      multipleSelection: [],
      formTitle: '',
      isEdit: false,
      OddNumberList: [],
      OutboundTypeList: [],
      platformOptions: [
        { label: '淘宝', value: '淘宝' },
        { label: '拍拍', value: '拍拍' },
        { label: '京东', value: '京东' },
        { label: '天猫', value: '天猫' },
        { label: '唯品会', value: '唯品会' },
        { label: '苏宁', value: '苏宁' },
        { label: '拼多多', value: '拼多多' },
        { label: '1688', value: '1688' }
      ],
      storeOptions: [
        { label: '', value: '' },
      ],
      CarrierList: [],
      dialogVisible: false,
      selectedCities: {},
      provinces: [],
      storeOptions: [], // 请填充店铺选项的数据
      selectedValues: []  // 用于存储选中的地区值
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getList()
    this.getCarrierList()
    this.getOddNumberList()
    this.getOutboundType()
    this.getRegion()
  },
  mounted() {},
  methods: {
    openDialog() {
      this.dialogVisible = true;
    },
    // 选择所有地区
    selectAll() {
      this.selectedValues = this.provinces.flatMap(province => [
        province.value, ...province.children.map(city => city.value)
      ]);
    },
    // 选择无地区
    selectNone() {
      this.selectedValues = [];
    },
    // 反选地区
    toggleSelection() {
      const allValues = this.provinces.flatMap(province => [
        province.value, ...province.children.map(city => city.value)
      ]);
      this.selectedValues = allValues.filter(value => !this.selectedValues.includes(value));
    },
    
    // 当选择城市时，自动选中该城市对应的省份
    onCityChange(province, city) {
      if (this.selectedValues.includes(city.value)) {
        // 如果城市被选中，选中对应的省份
        if (!this.selectedValues.includes(province.value)) {
          this.selectedValues.push(province.value);
        }
      } else {
        // 如果城市取消选择，取消省份的选择（如果没有其他城市选中该省份）
        const otherCitiesSelected = province.children.some(c => this.selectedValues.includes(c.value));
        if (!otherCitiesSelected) {
          const index = this.selectedValues.indexOf(province.value);
          if (index !== -1) {
            this.selectedValues.splice(index, 1);
          }
        }
      }
    },
    confirmSelection() {
      const selectedLabels = [];
      
      // 处理选中的省份
      this.selectedValues.forEach(value => {
        const province = this.provinces.find(p => p.value === value);
        if (province) {
          selectedLabels.push(province.label);  // 先加省份
        } else {
          // 选择的是城市
          this.provinces.forEach(p => {
            const city = p.children.find(c => c.value === value);
            if (city) {
              selectedLabels.push(city.label);  // 然后加城市
            }
          });
        }
      });
      
      // 填充文本框：确保省份在前，城市在后
      this.listQuery.PickingArea = selectedLabels.join(', ');  // 拼接选中的标签
      this.dialogVisible = false;  // 关闭对话框
    },
    getCarrierList(){
       this.$axios.gets("api/base/dictDetails/list?name="+"Carrier").then(response=>{
           this.CarrierList = response.items;
           console.log(this.CarrierList)
       })
    },
    getOddNumberList()
    {
      this.$axios.gets("api/base/dictDetails/list?name="+"OddNumber").then(response=>{
           this.OddNumberList = response.items;
           console.log(this.OddNumberList)
       })
    },
    getOutboundType()
    {
      this.$axios.gets("api/base/dictDetails/list?name="+"OutboundType").then(response=>{
           this.OutboundTypeList = response.items;
           console.log(this.OutboundTypeList)
       })
    },
    getRegion() {
      this.$axios.gets("api/business/Province/tree").then(response => {
        this.provinces = response.items;
        console.log(this.regions);
      });
    },
 
    getList() {
      this.listLoading = true;
      this.listQuery.SkipCount = (this.page - 1) * this.listQuery.MaxResultCount;
      const values = this.listQuery.SelectedValues;
      const valuesQuery = this.listQuery.Carrier;

      this.listQuery.SelectedValues = this.listQuery.SelectedValues.join(',');
      this.listQuery.Carrier = this.listQuery.Carrier.join(',');

      this.$axios.gets('/api/business/WaitingOutbound', this.listQuery).then(response => {
        this.list = response.items;
        this.totalCount = response.totalCount;
        this.listLoading = false;
        this.listQuery.SelectedValues = values;
        this.listQuery.Carrier = valuesQuery;

      });
    },
    fetchData(id) {
      this.$axios.gets('/api/business/WaitingOutbound/' + id).then(response => {
        this.form = response;
      });
    },
    handleFilter() {
      this.page = 1;
      this.getList();
    },
    handleCreate() {
      this.formTitle = '新增待出库';
      this.isEdit = false;
      this.dialogFormVisible = true;
    },
    handleDelete(row) {
      var params = [];
      let alert = '';
      if (row) {
        params.push(row.id);
        alert = row.name;
      }
      else {
        if (this.multipleSelection.length === 0) {
          this.$message({
            message: '未选择',
            type: 'warning'
          });
          return;
        }
        this.multipleSelection.forEach(element => {
          let id = element.id;
          params.push(id);
        });
        alert = '选中项';
      }
      this.$confirm('是否删除' + alert + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.posts('/api/business/WaitingOutbound/delete', params).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          });
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleUpdate(row) {
      this.formTitle = '修改待出库';
      this.isEdit = true;
      if (row) {
        this.fetchData(row.id);
        this.dialogFormVisible = true;
      }
      else {
        if (this.multipleSelection.length != 1) {
          this.$message({
            message: '编辑必须选择单行',
            type: 'warning'
          });
          return;
        }
        else {
          this.fetchData(this.multipleSelection[0].id);
          this.dialogFormVisible = true;
        }
      }
    },
    save() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.formLoading = true;
          this.form.roleNames = this.checkedRole;
          if (this.isEdit) {
            this.$axios.posts('/api/business/WaitingOutbound/data-post', this.form).then(response => {
              this.formLoading = false;
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              });
              this.dialogFormVisible = false;
              this.getList();
            }).catch(() => {
              this.formLoading = false;
            });
          }
          else {
            this.$axios.posts('/api/business/WaitingOutbound/data-post', this.form).then(response => {
              this.formLoading = false;
              this.$notify({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              });
              this.dialogFormVisible = false;
              this.getList();
            }).catch(() => {
              this.formLoading = false;
            });
          }
        }
      });
    },
    sortChange(data) {
      const {
        prop,
        order
      } = data;
      if (!prop || !order) {
        this.handleFilter();
        return;
      }
      this.listQuery.Sorting = prop + ' ' + order;
      this.handleFilter();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleRowClick(row, column, event) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    cancel() {
      this.form = Object.assign({}, defaultForm);
      this.dialogFormVisible = false;
      this.$refs.form.clearValidate();
    },
  }
}

</script>
<style scoped>
.content {
  padding: 20px;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  /* 让元素自动换行 */
}

.item {
  width: 100%;
  /* 确保省名称独占一行 */
  margin-bottom: 10px;
  /* 间距调整 */
}

.city-list {
  display: flex;
  flex-wrap: wrap;
  margin-left: 20px;
  float: right;
  /* 市名称缩进 */
}

.city-list el-checkbox {
  width: 150px;
  /* 控制市的宽度，确保同一行排列多个 */
  margin-right: 10px;
  /* 市之间的间距 */
}


</style>
